import { SearchOutlined } from '@ant-design/icons';
import { Button, Input, TableColumnsType, TableProps, Progress, message } from 'antd';
import React, { useEffect, useState, useRef } from 'react';
import UploadModal from './components/upload-modal/upload-modal';
import Tables from '@/components/tables/tables';
import { GetTestListType, StatusType } from '@/common/types';
import { formatDataWithSeconds } from '@/utils/time';
import { debounce } from 'lodash';
import useModal from '@/hooks/use-modal/useModal';
import PagesHeader from '@/components/pages-header';
import NotData from '@/components/NotData';
import TipsModals from '@/components/modals/TipsModals';
import { SvgIcon } from '@/components/icon';
import { downloadFetch } from '@/utils/system/utils';
import testService from '@/api/services/testService';

const statusTitle = {
  SUCCESS: '已完成',
  PROCESSING: '进行中',
  QUEUE: '排队中',
  FAIL: '错误',
};

const taskStatuslList = {
  SUCCESS: 0,
  PROCESSING: 1,
  QUEUE: 2,
  FAIL: -1,
};

const DocTypeManage = () => {
  const modal = useModal('import', 'deleteModal');
  const refreshTimer = useRef<NodeJS.Timeout | null>(null);

  // 分页信息
  const [pagingInfo, setPagingInfo] = useState({
    page: 1,
    pageSize: 10,
    searchText: '',
    offset: 0,
    isPage: true,
    status: [] as number[]
  });

  const [pagingTotal, setPagingTotal] = useState(0);
  const [tablesValue, setTablesValue] = useState<GetTestListType[]>([]);
  const [tableSelectEdRows, setTableSelectEdRows] = useState<React.Key[]>([]);
  const [progressFilter, setProgressFilter] = useState<{ text: string; value: number; }[]>([]);
  const [uploadError, setUploadError] = useState<string>('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [testingIds, setTestingIds] = useState<string[]>([]);

  // 判断选中的行中是否有不能下载的项目
  const hasUnDownloadableItems = () => {
    return tableSelectEdRows.some(key => {
      const item = tablesValue.find(row => row.id === key);
      return item && item.status !== 0;
    });
  };

  // 判断选中的行中是否有不能删除的项目
  const hasUnDeletableItems = () => {
    return tableSelectEdRows.some(key => {
      const item = tablesValue.find(row => row.id === key);
      return item && ![0, -1].includes(item.status);
    });
  };

  const searchParams = new URLSearchParams(location.search);
  const id = searchParams.get('appId') || '';

  // 表格多选
  const rowSelection: TableProps<GetTestListType>['rowSelection'] = {
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setTableSelectEdRows(newSelectedRowKeys);
    },
  };

  const columns: TableColumnsType<GetTestListType> = [
    { title: '任务名称', dataIndex: 'name' },
    { title: '测试文件名', dataIndex: 'exeFile' },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      render: (_, { startTime }) => <span>{startTime ? formatDataWithSeconds(startTime) : '-'}</span>,
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      render: (_, { endTime }) => <span>{endTime ? formatDataWithSeconds(endTime) : '-'}</span>,

    },
    { title: '创建账号', width: 150, dataIndex: 'creatorName' },
    {
      title: '任务进度',
      dataIndex: 'progress',
      filters: progressFilter,
      render: (_, record) => {
        return (
          <div>
            {record.status === -1 ? (
              <div className='flex gap-1'>
                <span className="text-error">错误：{record.message}</span>
                <span
                  className={`cursor-pointer ${testingIds.includes(record.id) ? 'text-gray-400 cursor-not-allowed' : 'text-primary'}`}
                  onClick={() => {
                    if (!testingIds.includes(record.id)) {
                      setTestingIds(prev => [...prev, record.id]);
                      resetTask(record.id);
                    }
                  }}
                >
                  {testingIds.includes(record.id) ? '提交中...' : '重试'}
                </span>
              </div>
            ) : record.status === 2 ? (
              <span className="text-info-500">任务{record.message != '-1' ? '排队' : '初始化'}中 {record.message && record.message != '-1' ? `预计等待${record.message || 0}分钟` : '预计等待时间正在计算中...'}</span>
            ) : (
              <div className="flex items-center gap-2">
                <Progress
                  className='!w-[150px]'
                  percent={record?.progress}
                  strokeColor="#01AF5C"
                  trailColor="#ADB2B0"
                  status="active"
                  format={(progress) => `${progress}%`}
                />
                {record.status != 0 && (
                  <span className="text-info-500">
                    {record.message && record.message != '-1'
                      ? `预计还需${record.message || 0}分钟`
                      : '预计完成时间正在计算中...'
                    }
                  </span>
                )}
              </div>
            )}
          </div>
        );
      },
    },
    {
      title: '准确率',
      dataIndex: 'accuracy',
      render: (accuracy, record) =>
        <span>{record.status == 0 ? `${accuracy}%` : '-'}</span>,
    },
    {
      title: '操作',
      key: 'action',
      width: 261,
      render: (_, record) => (
        <div className="flex">
          <Button
            type="text"
            onClick={() => {
              setTestingIds(prev => [...prev, record.id]);
              resetTask(record.id);
            }}
            disabled={record.status !== 0 || testingIds.includes(record.id)}
            loading={testingIds.includes(record.id)}
          >
            <SvgIcon icon="retry" size="16" className="mr-1" />
            {testingIds.includes(record.id) ? '提交测试中...' : '重新测试'}
          </Button>
          <Button
            type="text"
            onClick={() => hanldeDownload('only', record.id)}
            disabled={record.status !== 0}
          >
            <SvgIcon icon="download" size="16" className="mr-1" />
            下载
          </Button>
          <Button
            type="text"
            danger
            onClick={() => openDeleteModal('only', record.id)}
            disabled={!([0, -1].includes(record.status))}
          >
            <SvgIcon icon="message-ic3" size="16" className="mr-1" />
            删除
          </Button>
        </div>
      ),
    },
  ];

  // 获取列表数据
  const getList = () => {
    testService.GetListTask(id, pagingInfo).then((res) => {
      setTablesValue(res.list);
      setPagingTotal(res.total);
    });
  };

  // 获取筛选状态
  const getFilterTask = () => {
    testService.FilterTask(id).then((res) => {
      setProgressFilter(filterStatusTypeList(res.status));
    });
  };

  // 格式化状态筛选列表
  const filterStatusTypeList = (obj: object) => {
    return Object.entries(obj).map(([key, value]) => ({
      text: `${statusTitle[key as StatusType]}(${value})`,
      value: taskStatuslList[key as StatusType],
    }));
  };

  // 重试任务
  const resetTask = (id?: string) => {
    if (id) {
      testService.IssuedTask(id)
        .then(() => {
          getList();
        })
        .finally(() => {
          // 测试完成后，从测试中状态移除
          setTestingIds(prev => prev.filter(testId => testId !== id));
        });
    }
  };

  // 打开删除弹窗
  const openDeleteModal = (type?: string, id?: string) => {
    modal.deleteModal.open();
    if (type === 'only') {
      setTableSelectEdRows([id]);
    }
  };

  // 删除任务
  const deleteModalSubmit = () => {
    modal.deleteModal.startLoading();
    testService
      .DeleteTask({ taskIds: tableSelectEdRows as string[] })
      .then(() => {
        getList();
        setTableSelectEdRows([]);
      })
      .finally(() => {
        modal.deleteModal.stopLoading();
        modal.deleteModal.close();
      });
  };

  // 下载文件
  const hanldeDownload = async (type?: string, id?: string) => {
    let result: string[] = [];
    if (type === 'only') {
      if (!id) {
        message.error('任务ID不存在，无法下载');
        return;
      }
      result = [id];
    } else {
      result = tableSelectEdRows as string[];
    }

    if (result.length === 0) {
      message.error('请选择要下载的任务');
      return;
    }

    try {
      const downList = await testService.DownloadTest({ taskIds: result });
      if (downList.names && Array.isArray(downList.names)) {
        for (let i = 0; i < downList.names.length; i++) {
          downloadFetch({
            url: '/api/openapi/v2/app/test/file/result?resultFileName=' + downList.names[i],
            filename: downList.names[i]
          })
          if (i < downList.names.length - 1) {
            await new Promise(resolve => setTimeout(resolve, 500));
          }
        }
        getList();
      } else {
        message.error('导出失败，获取下载链接失败');
      }
    } catch (error) {
      console.error('下载失败:', error);
      message.error('下载失败，请重试');
    }
  };

  // 提交上传任务
  const uploadModalSubmit = (taskName: string, file: File) => {
    const formData = new FormData();
    formData.append('file', file.file);
    setUploadError('');
    setIsSubmitting(true);
    testService
      .CreateTask(id, taskName, formData)
      .then(() => {
        getList();
        modal.import.close();
        setUploadError('');
      })
      .catch((error) => {
        console.log(error, '---')
        setUploadError(error.message);
      })
      .finally(() => {
        modal.import.stopLoading();
        setIsSubmitting(false);
      });
  };

  // 搜索防抖处理
  const debounceSearch = debounce((value: string) => {
    setPagingInfo({ ...pagingInfo, searchText: value, page: 1, offset: 0 });
  }, 500);

  // 表格筛选变化
  const onChange: TableProps<GetTestListType>['onChange'] = (_, filters) => {
    setPagingInfo({
      ...pagingInfo,
      page: 1,
      status: (filters.progress as number[]) || []
    });
  };

  // 分页变化
  const handlePaginationChange = (page: number, pageSize: number) => {
    setPagingInfo({
      ...pagingInfo,
      page,
      pageSize: pageSize,
      offset: (page - 1) * pageSize
    });
  };

  // 初始化与定时刷新
  useEffect(() => {
    getList();
    getFilterTask();

    // 每秒刷新进度
    const timer = setInterval(getList, 5000);
    refreshTimer.current = timer;

    // 组件卸载时清除定时器
    return () => {
      if (refreshTimer.current) {
        clearInterval(refreshTimer.current);
      }
    };
  }, [pagingInfo]);

  return (
    <div className="flex h-full flex-col bg-white">
      <PagesHeader>应用测试</PagesHeader>
      <div className="pl-5 pb-3 text-cn-14 text-text-3">
        通过测试问题来测试应用的整体回答准确性是否达到标准
      </div>

      <div className="flex flex-1 flex-col rounded-lg bg-white px-5">
        <div className="my-4 flex items-center justify-between">
          <Input
            placeholder="搜索"
            suffix={<SvgIcon icon="work-ic6" size={16} />}
            className='!w-[240px]'
            onChange={(e) => debounceSearch(e.target.value)}
          />

          <div className="flex items-center">
            <div className="flex items-center">
              <div
                className="ml-[15px] flex py-[5px] px-2 cursor-pointer items-center justify-center rounded-md  border !border-@brand-color !text-@brand-color"
                onClick={modal.import.open}
              >
                新建测试任务
              </div>

              {tableSelectEdRows.length !== 0 && (
                <>
                  <div
                    className={`ml-[15px] flex py-[5px] px-2 items-center justify-center rounded-md border ${hasUnDownloadableItems()
                      ? 'cursor-not-allowed text-gray-400 border-gray-300'
                      : 'cursor-pointer text-@brand-color border-@brand-color'
                      }`}
                    onClick={hasUnDownloadableItems() ? undefined : () => hanldeDownload('all')}
                  >
                    下载
                  </div>
                  <div
                    className={`ml-[15px] flex py-[5px] px-2 items-center justify-center rounded-md border ${hasUnDeletableItems()
                      ? 'cursor-not-allowed text-gray-400 border-gray-300'
                      : 'cursor-pointer text-@error-color-hover border-@error-color-hover'
                      }`}
                    onClick={hasUnDeletableItems() ? undefined : () => openDeleteModal('all')}
                  >
                    删除
                  </div>
                </>
              )}
            </div>
          </div>
        </div>

        {tablesValue.length > 0 ? (
          <Tables
            rowSelection={{ type: 'checkbox', ...rowSelection }}
            rowKey="id"
            columns={columns}
            dataSource={tablesValue}
            pagination={false}
            paginationProps={{
              total: pagingTotal,
              current: pagingInfo.page,
              pageSize: pagingInfo.pageSize,
              onChange: handlePaginationChange,
            }}
            onChange={onChange}
          />
        ) : (
          <NotData />
        )}
      </div>

      {/* 删除确认弹窗 */}
      <TipsModals
        open={modal.deleteModal.isOpen}
        onOk={deleteModalSubmit}
        onCancel={modal.deleteModal.close}
        confirmLoading={modal.deleteModal.isLoading}
      >
        删除后无法恢复,确认删除?
      </TipsModals>

      {/* 上传弹窗 */}
      <UploadModal
        open={modal.import.isOpen}
        onCancel={modal.import.close}
        onFileOk={uploadModalSubmit}
        confirmLoading={modal.import.isLoading}
        uploadError={uploadError}
        isSubmitting={isSubmitting}
      />
    </div>
  );
};

export default DocTypeManage;